//
//  NotificationCreateViewController.m
//  MapLink
//
//  Created by student on 5/19/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "NotificationCreateViewController.h"
#import "JSON/JSON.h"
#import "NetworkManager.h"


@implementation NotificationCreateViewController

@synthesize btnSend, btnCancel, txtMessage, lblWordCount, buffer;
@synthesize groupName, displayName, deviceID, currentLocation;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}

- (id) init {
	self = [self initWithNibName:@"NotificationCreateViewController" bundle:nil];
	return self;
}

- (void)textViewDidChange:(UITextView *)textView {
	[self updateWordCount];
}

- (IBAction) updateWordCount {
	if ([txtMessage.text length] == 0) {
		lblWordCount.text = @"Please start typing your message!";
	} else {
		lblWordCount.text = [NSString stringWithFormat:@"Word Count: %d",[txtMessage.text length]];
	}
}

- (IBAction) clickedCancel {
	[self dismissModalViewControllerAnimated:YES];
}

- (IBAction) clickedSend {
	if (![NetworkManager connectedToNetwork]) 
	{
		// Network is not available
		lblWordCount.text = @"ERROR: Network is not available!!";
		return;
	}
	
	if ([txtMessage.text length] == 0) {
		lblWordCount.text = @"You have to type your message first!";
		return;
	}
	
	btnSend.enabled = NO;
	[activityIndicatorView startAnimating];
	
	lblWordCount.text = @"Sending your message...";
	
	NSString *strRequest = @"http://mybuddies.emiu.net/postmessage.php?device_id=%@&name=%@&group=%@&latitude=%d&longitude=%d&message=%@";
	NSString *strMessage = [txtMessage.text stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
	
	NSString *urlString = [NSString stringWithFormat:strRequest,
						   [deviceID stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
						   [displayName stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
						   [groupName stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
						   (int)(currentLocation.latitude*1e6),
						   (int)(currentLocation.longitude*1e6),
						   strMessage];
	NSURL *url = [NSURL URLWithString:urlString];
	NSLog(@"URL:%@",urlString);
	
	if(!url) {
		// error in creating NSURL object
	} else {
		NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
		if (!req) {
			// error in creating Request object
		} else {
			[req setHTTPMethod:@"GET"];
			conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
			if (conn) {
				self.buffer = [NSMutableData data]; 
			}
		}
	}	
}

/* START: Connection delegate */
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
	[buffer setLength:0];
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
	[buffer appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
	[buffer release];
	[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
	NSLog(@"Done with bytes %d", [buffer length]);

	NSMutableString *jsonString = [[NSMutableString alloc] initWithBytes:[buffer mutableBytes]
																  length:[buffer length]
																encoding:NSUTF8StringEncoding];
	NSDictionary *response = [jsonString JSONValue];
	NSString *result = [response objectForKey:@"result"];
	NSString *error = [response objectForKey:@"message"];
	
	[activityIndicatorView stopAnimating];
	
	if ([result isEqualToString:@"Y"]) {
		// Successful
		lblWordCount.text = @"Sent!";
		[self dismissModalViewControllerAnimated:YES];
	} else {
		// Error
		lblWordCount.text = [NSString stringWithFormat:@"ERROR: %@",error];
	}
	
	btnSend.enabled = YES;
	
	[jsonString release];
	[connection release];
}
/* END: Connection delegate */


/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void) viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	lblWordCount.text = @"Please start typing your message!";
	txtMessage.text = @"";
	btnSend.enabled = YES;
	[txtMessage becomeFirstResponder];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	if (buffer) [buffer release];
	if (deviceID) [deviceID release];
	if (groupName) [groupName release];
	if (displayName) [displayName release];
	if (buffer) [buffer release];
	if (buffer) [buffer release];
	if (buffer) [buffer release];
	
    [super dealloc];
}


@end
